using ChatBackend.Models;
using SqlSugar;
using DbType = SqlSugar.DbType;

namespace ChatBackend.Scripts
{
    public static class ResetDatabase
    {
        public static void Reset(string connectionString)
        {
            var db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = connectionString,
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                MoreSettings = new ConnMoreSettings()
                {
                    IsAutoRemoveDataCache = true,
                    IsWithNoLockQuery = true,
                    DisableNvarchar = true
                },
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    EntityService = (c, p) =>
                    {
                        if (p.DataType == "datetime")
                        {
                            p.DataType = "TEXT";
                        }
                    }
                }
            });

            try
            {
                Console.WriteLine("开始重置数据库...");

                // 删除所有表
                db.DbMaintenance.DropTable<UserChatRoom>();
                db.DbMaintenance.DropTable<Message>();
                db.DbMaintenance.DropTable<ChatRoom>();
                db.DbMaintenance.DropTable<User>();

                Console.WriteLine("已删除所有表");

                // 重新创建表
                db.CodeFirst.InitTables(
                    typeof(User),
                    typeof(ChatRoom),
                    typeof(Message),
                    typeof(UserChatRoom)
                );

                Console.WriteLine("已重新创建所有表");

                // 创建测试数据
                CreateTestData(db);

                Console.WriteLine("数据库重置完成");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"重置数据库时出错: {ex.Message}");
                throw;
            }
            finally
            {
                db.Dispose();
            }
        }

        private static void CreateTestData(ISqlSugarClient db)
        {
            // 创建测试用户
            var users = new List<User>
            {
                new User
                {
                    Username = "admin",
                    Email = "admin@example.com",
                    DisplayName = "管理员",
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword("123456"),
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                },
                new User
                {
                    Username = "alice",
                    Email = "alice@example.com",
                    DisplayName = "Alice",
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword("123456"),
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                },
                new User
                {
                    Username = "bob",
                    Email = "bob@example.com",
                    DisplayName = "Bob",
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword("123456"),
                    CreatedAt = DateTime.UtcNow,
                    UpdatedAt = DateTime.UtcNow
                }
            };

            db.Insertable(users).ExecuteCommand();
            Console.WriteLine("已创建测试用户");

            // 创建测试聊天室
            var chatRoom = new ChatRoom
            {
                Name = "测试聊天室",
                Description = "这是一个测试聊天室",
                Type = ChatRoomType.Group,
                CreatedAt = DateTime.UtcNow,
                UpdatedAt = DateTime.UtcNow
            };

            var chatRoomId = db.Insertable(chatRoom).ExecuteReturnIdentity();
            Console.WriteLine($"已创建测试聊天室，ID: {chatRoomId}");

            // 添加用户到聊天室
            var userChatRooms = new List<UserChatRoom>
            {
                new UserChatRoom
                {
                    UserId = 1,
                    ChatRoomId = (int)chatRoomId,
                    Role = UserRole.Admin,
                    JoinedAt = DateTime.UtcNow
                },
                new UserChatRoom
                {
                    UserId = 2,
                    ChatRoomId = (int)chatRoomId,
                    Role = UserRole.Member,
                    JoinedAt = DateTime.UtcNow
                },
                new UserChatRoom
                {
                    UserId = 3,
                    ChatRoomId = (int)chatRoomId,
                    Role = UserRole.Member,
                    JoinedAt = DateTime.UtcNow
                }
            };

            db.Insertable(userChatRooms).ExecuteCommand();
            Console.WriteLine("已添加用户到聊天室");

            // 创建测试消息
            var messages = new List<Message>
            {
                new Message
                {
                    ChatRoomId = (int)chatRoomId,
                    SenderId = 1,
                    Content = "欢迎来到测试聊天室！",
                    Type = MessageType.Text,
                    CreatedAt = DateTime.UtcNow
                },
                new Message
                {
                    ChatRoomId = (int)chatRoomId,
                    SenderId = 2,
                    Content = "谢谢！很高兴加入这里。",
                    Type = MessageType.Text,
                    CreatedAt = DateTime.UtcNow.AddMinutes(1)
                }
            };

            db.Insertable(messages).ExecuteCommand();
            Console.WriteLine("已创建测试消息");
        }
    }
}
